from flask import Flask,request
import json

from fw_shell import runCmd
from processChain import processChain
from Rule import getAddRuleCmd,getDeleteRuleCmd
from firewall_interface import Rule

print('server~')

app = Flask(__name__)

@app.after_request
def cors(environ):#解决跨域问题
    environ.headers['Access-Control-Allow-Origin']='*'
    environ.headers['Access-Control-Allow-Method']='*'
    environ.headers['Access-Control-Allow-Headers']='x-requested-with,content-type'
    return environ

@app.route('/add-rule',methods=['POST'])
def addrule():
    rule=request.form['rule']
    rule_json = json.loads(rule)

    print(rule_json)

    cmd = getAddRuleCmd(Rule(rule_json))

    if cmd == -1:
        return 'error in forming cmd'

    ret = runCmd(cmd)

    if ret.returncode == 0:
        return 'succeed'
    else:
        return 'error in running cmd'



@app.route('/delete-rule',methods=['POST'])
def deleterule():
    rule=request.form['rule']
    rule_json = json.loads(rule)
    print(rule_json)

    cmd = getDeleteRuleCmd(rule_json['chain'],rule_json['num'])

    if cmd == -1:
        return 'error in forming cmd'

    ret = runCmd(cmd)
    if(ret.returncode == 0):
        return 'succeed'
    else:
        return 'error in running cmd'



@app.route('/refresh-rules')
def refreshRule():
    tables = []

    result = runCmd('iptables -nvL INPUT --line-numbers')

    if(result.returncode == 0):
        tables.append( processChain(result.stdout.splitlines()))
    else:
        return 'error'


    result = runCmd('iptables -nvL OUTPUT --line-numbers')

    if(result.returncode == 0):
        tables.append( processChain(result.stdout.splitlines()))
    else:
        return 'error'
    
    return json.dumps(tables)


if __name__ == '__main__':
   app.run(debug = True,port=8095)